package com.hundsun.cprs.yyt.web.action.common;

import java.util.Map;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.hundsun.cprs.yyt.service.plate.domain.PlateImage;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;

import com.alibaba.fastjson.JSON;
import com.hundsun.cprs.yyt.common.fileUpload.FileUploadUtil;
import com.hundsun.cprs.yyt.util.BeanUtils;
import com.hundsun.cprs.yyt.util.UploadUtil;
import com.hundsun.cprs.yyt.web.action.BaseAction;
import com.hundsun.cprs.yyt.web.vo.ImageVo;
import com.hundsun.cprs.yyt.web.vo.UploadImageResult;

/**
 * 用于前端公共的操作，如图片上传，选择用户等
 * 
 * @author linrl
 * @date 2018年5月16日
 */
@Controller
@RequestMapping("common")
public class CommonAction extends BaseAction {
    
    @Resource(name = "imageUploadUtil")
    private FileUploadUtil fileUploadUtil;

    @RequestMapping("image/upload")
    public @ResponseBody String uploadImage(HttpServletRequest request, HttpServletResponse response, 
            ModelMap model,@RequestParam("moduleType") String moduleType) {
        response.setContentType("text/html;charset=UTF-8");
        UploadImageResult result = new UploadImageResult();
        MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest)request;
        Map<String, MultipartFile> fileMap = multipartRequest.getFileMap();
        for (Map.Entry<String, MultipartFile> entity : fileMap.entrySet()) {
            // 获取MulipartFile对象
            MultipartFile upfile = entity.getValue();
            ImageVo imageVo = upLoad(upfile,moduleType);
            if(imageVo != null){
                result.setSuccess(true);
                result.getResult().add(imageVo);
            }
        }
        return JSON.toJSONString(result);
    }
    
    private ImageVo upLoad(MultipartFile upfile,String moduleType){
        if (UploadUtil.ifFileSizePermitted(upfile, FileUploadUtil.MAX_IMAG_SIZE, FileUploadUtil.MAX_FILE_SIZE)) {
            PlateImage goodsImage = new PlateImage();
            fileUploadUtil.uploadFile(goodsImage,upfile, moduleType);
            return BeanUtils.transfrom(ImageVo.class, goodsImage);
        }else{
            log.error(upfile.getName() + "图片大小不能超过" + FileUploadUtil.MAX_IMAG_SIZE / 1024 / 1024 + "M");
            return null;
        }
    }
}
